import { showSuccessToast } from 'vant';
import { ref } from 'vue';

import { deserialize } from '@/plugins/reflect-metadata';
import useUserStore from '@/stores/user.store';

import { getUserBalance } from '../api';
import BalanceInfo from '../models/BalanceInfo';

const useRefreshBal = () => {
  const loading = ref(false);
  const userStore = useUserStore();

  const fetchData = async () => {
    try {
      loading.value = true;
      const { data } = await getUserBalance();
      const resultData = deserialize(data.data, BalanceInfo);
      userStore.userInfo.balance = resultData.balance;
      userStore.userInfo.freezeBalance = resultData.freezeBalance;
      showSuccessToast(data.msg || '余额刷新成功');
    } catch (error) {
      //
    } finally {
      setTimeout(() => {
        loading.value = false;
      }, 1500);
    }
  };

  return {
    loading,
    fetchData,
  };
};

export default useRefreshBal;
